<?php

require_once('BaseModel.php');

class Categorias extends BaseModel{
	protected $_name =  "categorias";

	function getCatsOperationId( $parentId, $site_id = NULL ){
		if( !$site_id ){
			$site_id = $this->_site['id'];
		}

		return $this->getName().'_parent'.$parentId.'site_'.$site_id;
	}

	function getOperationTags( $site_id = NULL  ){
		if( !$site_id ){
			$site_id = $this->_site['id'];
		}
		return array( $this->getName(), 'tree', 'site_'.$site_id );
	}

	function cleanCache(){
		$this->_cache->clean( 
    		Zend_Cache::CLEANING_MODE_MATCHING_TAG,
			$this->getOperationTags()
		);
	}
	
	function getCategoriasTree( $optionsPassed = array() ){
		
		$sites_id = $this->_site['id'];
		
		$options = array(
			'depth' => '', 'child_of' => 0, 'exclude' => '', 'all'=>false
		);
		
		$options = array_merge( $options, $optionsPassed );

		$all = $options['all'];

		$operationId = $this->getCatsOperationId( $options['child_of'], $sites_id );
		$operationTags = $this->getOperationTags( $sites_id );
		
		if( $this->_cache->test( $operationId) ){
			$data = $this->_cache->load( $operationId );
		} else {
			$this->setQuantidadePaginacao( 1000 );

			$select = $this->getSelectObject();
			$select->where("status != ?", 2);
			$select->where("sites_id = ?", $sites_id );

			$select->order( array( 'posicao ASC ' ));

			$select->where("pai = ?", $options['child_of'] );

			$this->setSelectObject( $select );

			$data = $this->getAll();
			$this->_cache->save( $data, $operationId, $operationTags );
			
			$this->unsetSelectObject();
		}

		$dataReturn = array();
		$i=0;
		foreach( $data as $c ){
			if( !$all && $c['status'] == 0){
				continue;
			}
			
			$dataReturn[$c['id']] = $c;
			$dataReturn[ $c['id'] ]['childs'] = array();

			if( $i <= $options['depth'] || $options['depth'] == '' ){
				$cats = $this->getCategoriasTree( array( 'child_of'=>$c['id'], 'all'=>$all ) );
				$dataReturn[ $c['id'] ]['childs'] = $cats;
			}

			$i++;
		}
		
		return $dataReturn;
	}
}